rust 使用hotwatch 监控文件变化

您所在的位置:网站首页 php 监控文件夹变动怎么办 rust 使用hotwatch 监控文件变化

rust 使用hotwatch 监控文件变化

2024-07-05 01:46| 来源: 网络整理| 查看: 265

hotwatch是一个可以监控文件变化的crate,使用起来非常方便。参考:GitHub - francesca64/hotwatch: A Rust library for conveniently watching and handling file changes.

监控单个文件

的代码示例如下:

use std::{thread::sleep, time::Duration}; fn main() { use hotwatch::{Event, Hotwatch}; let mut hotwatch = Hotwatch::new().expect("hotwatch failed to initialize!"); hotwatch .watch("test.txt", |event: Event| { println!("get some event {:?}",event); if let Event::Write(path) = event { println!("test.txt has changed.{:?}",path); } }) .expect("failed to watch file!"); loop { sleep(Duration::from_secs(2)); } }

在windows下,修改一个文件,hotwatch会先捕获到一个NoticeWrite事件,再捕获到一个Write事件。这是符合我们预期的。

但是在linux下会有一个坑。如果用vim修改这个文件,hotwatch仅仅会捕获到一个NoticeRemove事件,而且之后再也捕获不到任何事件。参考

unable to watch file edits by vim · Issue #247 · notify-rs/notify · GitHub

这可能是跟vim修改文件的机制有关,猜测vim是先整个test.txt.swap临时文件,然后当wq保存时将test.txt删掉再把test.txt.swap重名名为test.txt。 

如果使用echo "xxx">>test.txt 的方式修改文件,hotwatch是可以正常观测的。

监控整个目录

由于监控单个文件会有上述问题,所以当我们想要关注单个文件变化的时候,最好还是要监控整个目录。示例代码如下:

use std::{thread::sleep, time::Duration}; fn main() { use hotwatch::{Event, Hotwatch}; let mut hotwatch = Hotwatch::new().expect("hotwatch failed to initialize!"); hotwatch .watch("./", |event: Event| { println!("get some event {:?}",event); if let Event::Write(path) = event { if path.file_name().unwrap().to_str().unwrap().eq("test.txt") { println!("test.txt has changed.{:?}",path); } else{ println!("other file has been changed!{:?}",path); } } }) .expect("failed to watch file!"); loop { sleep(Duration::from_secs(2)); } }

在Linux下用vim编辑单个文件,结果如下:

可以看出来,vim修改文件的机制与上文猜想的一致。

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3